<?php

namespace App\Kuafu\Mybank\Service;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Config\Model\ConfigModel;
use App\Kuafu\Config\Service\ConfigService;
use App\Kuafu\Mybank\Enum\MybankIncomeCacheEnum;
use App\Kuafu\Mybank\Model\MybankBatchNoRecordModel;
use App\Kuafu\Mybank\Model\MybankBillRecordBindModel;
use App\Kuafu\Mybank\Model\MybankBillRecordModel;
use App\Kuafu\Mybank\Model\MybankEntryModel;
use App\Kuafu\Mybank\Model\MybankFuyouBillRecordModel;
use App\Kuafu\Mybank\Model\MybankShopBindModel;
use App\Kuafu\Mybank\Model\MybankVostroBillModel;
use App\Kuafu\Mybank\Model\MybankWalletRecordModel;
use App\Kuafu\Mybank\Resources\MybankEntryDetailResource;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Kuafu\Pay\Model\RefundStreamModel;
use App\Kuafu\Pay\Service\ShopPayService;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Resources\B\ShopSimpleResource;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Library\FeiShu\SendFs;
use App\Remote\Mybank\MybankAccountRemote;
use App\Remote\Mybank\MybankCreateBatchRemote;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Kuafu\GeneralFs\BuildFs;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class MybankBrokerageService extends BaseService
{

    /**
     * 获取指定的分佣比例
     *
     * @param string $key
     * @return array|mixed
     */
    public static function getMybankBrokerage(string $key = 'default')
    {
        $config = ConfigModel::getConfigByTypeKeyOne('mybankBrokerage', $key);

        if ($config) {
            return json_decode($config->value, 1);
        }

        return [];
    }


    /**
     * 添加当月的实收
     *
     * @param int $shopId
     * @param int $price
     * @param string $yearMonth
     * @return mixed
     */
    public static function incShopAllIncomeMonthWithCache(int $shopId, int $price, string $yearMonth = '')
    {
        return Redis::connection()->INCRBY(MybankIncomeCacheEnum::getMonthIncomeKey($shopId, $yearMonth), $price);
    }

    /**
     * 获取某月的总实收 带缓存
     *
     * @param int $shopId
     * @param string $yearMonth
     * @param bool $forceUpdate
     * @return array
     */
    public static function getShopAllIncomeMonthWithCache(
        int $shopId,
        string $yearMonth = '',
        bool $forceUpdate = false
    ): array {
        $isNew        = false;
        $yearMonth    = $yearMonth ?: date('Ym');
        $key          = MybankIncomeCacheEnum::getMonthIncomeKey($shopId, $yearMonth);
        $redisConnect = Redis::connection();
        $sumPrice     = $redisConnect->get($key) ?? 0;
        if ($forceUpdate || !$sumPrice) {
            $yearMonthCarbon  = Carbon::createFromTimestamp(strtotime($yearMonth . '01'));
            $startAtTimestamp = $yearMonthCarbon->startOfMonth()->getTimestamp();
            $endAtTimestamp   = $yearMonthCarbon->endOfMonth()->getTimestamp();
            $sumPrice         = MybankBrokerageService::getShopAllIncomeMonth($shopId, $startAtTimestamp,
                $endAtTimestamp);
            $redisConnect->set($key, $sumPrice, 'ex', 60 * 86400); // 60 天有效期
            $isNew = true;
        }
        return [
            'sumPrice' => (int)$sumPrice,
            'isNew'    => $isNew
        ];
    }

    /**
     * 获取某月的总实收 带缓存
     *
     * @param int $shopId
     * @param string $yearMonth
     * @return bool
     */
    public static function forgetShopAllIncomeMonthCache(int $shopId, string $yearMonth = ''): bool
    {
        $key = MybankIncomeCacheEnum::getMonthIncomeKey($shopId, $yearMonth);
        Redis::connection()->del($key);
        return true;
    }

    public static function refreshShopAllIncomeMonthCache(int $shopId): array
    {
        return MybankBrokerageService::getShopAllIncomeMonthWithCache($shopId, '', true);
    }

    /**
     * 获取某月的总实收 无缓存
     *
     * @param int $shopId
     * @param int $startAt
     * @param int $endAt
     * @return int|mixed
     */
    public static function getShopAllIncomeMonth(int $shopId, int $startAt, int $endAt)
    {
        // 获取外卖总实收
        $wmIncome = self::getShopWmIncomeMonth($shopId, $startAt, $endAt);

        // 获取堂食总实收
        $tsIncome = self::getShopTsIncomeMonth($shopId, $startAt, $endAt);

        $allIncome = $wmIncome + $tsIncome;

//        dump('外卖总实收:' . $wmIncome);
//        dump('堂食总实收:' . $tsIncome);
//        dump('总实收:' . $allIncome);

        return $allIncome;
    }


    /**
     * 外卖总实收
     *
     * @param int $shopId
     * @param int $startAt
     * @param int $endAt
     * @return mixed
     */
    public static function getShopWmIncomeMonth(int $shopId, int $startAt, int $endAt)
    {
        // 获取外卖总实收
        $wmIncome = WaiMaiOrderModel::suffix($shopId)
                                    ->whereBetween('createdAt', // 外卖用创建时间
                                        [$startAt, $endAt])
                                    ->where('shopId', $shopId)
                                    ->where('orderStatus', '!=', WaiMaiDBEnum::ORDER_STATUS_7)
                                    ->sum('expectIncome');

        return $wmIncome;
    }


    /**
     * 堂食总实收
     *
     * @param int $shopId
     * @param int $startAt
     * @param int $endAt
     * @return int|mixed
     */
    public static function getShopTsIncomeMonth(int $shopId, int $startAt, int $endAt)
    {
        $tsIncome = OrderSplitModel::suffix($shopId)
                                   ->query()
                                   ->where('shopId', $shopId)
                                   ->where('orderStatus', CodeEnum::ORDER_STATUS_FINISHED)
                                   ->whereBetween('completeTime', [$startAt, $endAt])
                                   ->sum('realPayPrice');


//        $tsIncome = PayStreamModel::suffix($shopId)
//                                  ->query()
//                                  ->where('shopId', $shopId)
//                                  ->where('sysType', PayStreamModel::SYS_TYPE_RMS_MEAL)
//                                  ->whereIn('payChannel',
//                                      [PayStreamModel::PAY_CHANNEL_FY, PayStreamModel::PAY_CHANNEL_CASH])
//                                  ->whereBetween('paySuccessTime', [$startAt, $endAt])
//                                  ->where('payStatus', PayStreamModel::PAY_STATUS_1)
//                                  ->sum('payPrice');
        // 暂时不考虑退款金额

//        $tsRefund = RefundStreamModel::query()
//                                     ->where('shopId', $shopId)
//                                     ->where('sysType', PayStreamModel::SYS_TYPE_RMS_MEAL)
//                                     ->where('refundStatus', RefundStreamModel::REFUND_STATUS_OK)
//                                     ->where('refundSuccessTime')
//                                     ->sum('refundPrice');

        //

        return $tsIncome;
    }

    public static function getPercentByDefaultConfig(int $shopId, int $sumPayPrice)
    {
        // 通过支付配置获取分账金额
        $percentConfig = ShopPayService::getPayConfigCache($shopId, PayStreamModel::PAY_CHANNEL_MYBANK_CONFIG);

        // 永久关闭
        $isStop = $percentConfig['isStop'] ?? false;

        // 临时暂停
        $isPause = $percentConfig['isPause'] ?? false;

        if ($isStop || $isPause) {
            return '0';
        }

        $percentConfig = $percentConfig['rule'] ?? $percentConfig;

        if (empty($percentConfig) || count($percentConfig) <= 0) {
            BuildFs::newRobot(SendFs::ROBOT_WARNING)
                   ->setTitleContent('未找到shopPayment分账配置', "shopId: {$shopId}")
                   ->setAtUid('3fgc8798')
                   ->setAtUid('9efgbcdb')
                   ->send();
            $percentConfig = self::getMybankBrokerage();
        }

        $percent = 0;
        foreach ($percentConfig as $item) {
            if ($sumPayPrice > $item['startPrice'] && $sumPayPrice <= $item['endEqPrice']) {
                $percent = $item['percent'];
            }
        }
        if ($percent === 0) {
            $percent = end($percentConfig)['percent'];
        }

        return $percent;
    }


}
